package com.cool.modules.finance.service.coin.impl;

import cn.hutool.core.util.StrUtil;
import com.cool.core.base.BaseServiceImpl;
import com.cool.core.exception.CoolException;
import com.cool.modules.finance.entity.account.FinanceAccountEntity;
import com.cool.modules.finance.entity.coin.FinanceCoinEntity;
import com.cool.modules.finance.entity.order.FinanceOrderEntity;
import com.cool.modules.finance.mapper.account.FinanceAccountMapper;
import com.cool.modules.finance.mapper.coin.FinanceCoinMapper;
import com.cool.modules.finance.mapper.order.FinanceOrderMapper;
import com.cool.modules.finance.service.coin.FinanceCoinService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class FinanceCoinServiceImpl extends BaseServiceImpl<FinanceCoinMapper, FinanceCoinEntity> implements FinanceCoinService {

    final FinanceAccountMapper accountMapper;

    final FinanceOrderMapper orderMapper;

    @Override
    public Long add(FinanceCoinEntity entity) {
        if (exists(new QueryWrapper().eq(FinanceCoinEntity::getCoinCode,entity.getCoinCode()))){
            throw new CoolException("该币种已存在");
        }
        entity.setCoinCode(entity.getCoinCode().toUpperCase());
        return super.add(entity);
    }

    @Override
    public boolean update(FinanceCoinEntity entity) {
        entity.setCoinCode(entity.getCoinCode().toUpperCase());
        return super.update(entity);
    }

    @Override
    public boolean delete(Long... ids) {
        for (int i = 0; i < ids.length; i++) {
            long accountCoinCount = accountMapper.selectCountByQuery(new QueryWrapper().eq(FinanceAccountEntity::getCoinId, ids[i]));
            long orderCoinCount = orderMapper.selectCountByQuery(new QueryWrapper().eq(FinanceOrderEntity::getCoinId, ids[i]));
            if (accountCoinCount > 0|| orderCoinCount > 0){
                throw new CoolException("该币种已被使用，不能删除");
            }
        }
        return super.delete(ids);
    }
}
